import traceback

import docker

from harbor_api import Harbor_API

SOURCE_HOST = "172.22.63.220"
SOURCE_PORT = "8000"
SOURCE_USER = "admin"
SOURCE_PASS = "aAFl3gHQwPvWsczGyVhD9vA7"

TARGET_HOST = "172.22.63.225"
TARGET_PORT = "18000"
TARGET_USER = "admin"
TARGET_PASS = "aAFl3gHQwPvWsczGyVhD9vA7"

# client = docker.APIClient(base_url="tcp://127.0.0.1:2375")
client = docker.APIClient(base_url="tcp://172.22.63.225:12375")

def build_port_url(host, port):
    if port == "80":
        return host
    return f"{host}:{port}"

client.login(username=TARGET_USER, password=TARGET_PASS, registry=f"http://{build_port_url(TARGET_HOST, TARGET_PORT)}")


def sync_image(image, ignore_list=[]):
    source_url = build_port_url(SOURCE_HOST, SOURCE_PORT)
    image_name = image[len(source_url):]
    target_url = build_port_url(TARGET_HOST, TARGET_PORT)
    target_image = f"{target_url}{image_name}"
    if target_image in ignore_list:
        print(f"{image} => {target_image} is in ignore list")
        return
    print(f"{image} => {target_image}")
    # output = client.pull(image)
    for line in client.pull(image, stream=True, decode=True):
        pull_id = line.get('id', '')
        progress = line.get('progress', '')
        print(f"\rPULL {pull_id}\t{progress}", end='', flush=True)
    print(f"{image}")
    images = client.images(name=image)
    select_image = images[0]
    client.tag(image=select_image["Id"], repository=target_image.split(":")[0], tag=target_image.split(":")[1])
    push_res = client.push(target_image, stream=True, decode=True)
    for line in push_res:
        push_id = line.get('id', '')
        progress = line.get('progress', '')
        print(f"\rPUSH {push_id}\t{progress}", end='', flush=True)
    print(f"{target_image}")
    try:
        client.remove_image(image)
        client.remove_image(target_image)
    except Exception as e:
        print(f"Failed to remove image: {e}")



if __name__ == '__main__':
    harbor_api = Harbor_API(SOURCE_HOST, SOURCE_PORT, SOURCE_USER, SOURCE_PASS, ignore80=True)
    alls = harbor_api.get_all_artifacts(["alg"])

    target_api = Harbor_API(TARGET_HOST, TARGET_PORT, TARGET_USER, TARGET_PASS, ignore80=True)
    ta_all = target_api.get_all_artifacts()

    for image in alls:
        sync_image(image, ta_all)
